#include <iostream>
#include <ctime>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main() {
    // 创建套接字
    int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == -1) {
        perror("Socket creation failed");
        return -1;
    }

    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(123);  // NTP默认端口123
    serverAddr.sin_addr.s_addr = INADDR_ANY;

    // 绑定套接字
    if (bind(serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) {
        perror("Bind failed");
        close(serverSocket);
        return -1;
    }

    // 监听套接字
    if (listen(serverSocket, 5) == -1) {
        perror("Listen failed");
        close(serverSocket);
        return -1;
    }

    std::cout << "NTP server is listening..." << std::endl;

    // 接受连接
    struct sockaddr_in clientAddr;
    socklen_t clientAddrLen = sizeof(clientAddr);
    int clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddr, &clientAddrLen);
    if (clientSocket == -1) {
        perror("Accept failed");
        close(serverSocket);
        return -1;
    }

    std::cout << "Client connected" << std::endl;

    // 获取当前时间
    time_t now;
    time(&now);
    struct tm *currentTime = localtime(&now);

    // 这里简单处理时间格式，实际NTP时间格式更复杂
    char timeBuffer[26];
    strftime(timeBuffer, 26, "%Y-%m-%d %H:%M:%S", currentTime);

    // 发送时间给客户端
    if (send(clientSocket, timeBuffer, strlen(timeBuffer), 0) == -1) {
        perror("Send failed");
    }

    close(clientSocket);
    close(serverSocket);
    return 0;
}